<?php 
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
include('/application/libraries/aliyun-dysms-php-sdk/api_demo/SmsDemo.php'); //这个是你下面实例化的类
include('DesUtils.php');
class Userapi extends CI_Controller {
	/**
	 * 判断递交方法
	 *
	 * @param	IS_POST	//新增
	 * @param	IS_GET	//查询
	 * @param	IS_PUT  //修改
	 * @param	IS_DEL  //删除
	 *
	 * @param	$this->load->model('Model_m');  // 实例 增删改查 的模型
     * @param	$user_IP = $this->Model_m->select('app_auth',$ip_where,'id desc','1,1');  1//app_auth 数据表  2//$ip_where where数组 3//正序倒序  4//limit
	 * 	
     *
	 */

	public function __construct(){
		parent::__construct();
		//header('Content-Type: application/json; charset=utf-8');
		$this->load->helper(array('form', 'url'));
		$this->load->model('Model_m');// 第三方 实例 增删改查 的模型
		// $this->load->model('Model_m');// 第三方 实例 增删改查 的模型
		$this->load->model('Device_m');// 第三方 实例 增删改查 的模型
		$this->load->model('Config_m');// 第三方 实例 增删改查 的模型
		$this->load->model('Usersweixin_m');// 第三方 实例 增删改查 的模型
		$this->load->model('Recharge_m');// 第三方 实例 增删改查 的模型
		$this->load->library('api/userapi_service');// 用户中间层 实例 增删改查 的模型
		$this->load->library('session');
		
	}
	
	//wifi.qianlh.com/Mobile/Userapi/user_api
	//http://www.mifi.com/Mobile/Userapi/user_api?user_id=10000	 
    public function user_api(){
		$user = $this->session->userdata('user');

    	switch ($_SERVER["REQUEST_METHOD"]) {
			case 'GET':
				
				break;
			case 'POST':
				
				$post['device_sn'] = $this->input->post('device_sn');
				$post['carid'] = $this->input->post('carid');
				$post['mobile'] = $this->input->post('mobile');
				$post['realname'] = $this->input->post('realname');
				$post['username_qq'] = $this->input->post('qq');
				$post['carid_image_z'] = $this->input->post('carid_image_z');
				$post['carid_image_f'] = $this->input->post('carid_image_f');
				$post['carid_image_s'] = $this->input->post('carid_image_s');
				$post['password'] = substr(md5($this->input->post('qq')),0,6);
				$post['user_id'] = $user[0]['user_id'];
				
				if(empty($post['device_sn'])){
					$data['success'] = error(4010); //请求要求成功返回信息
      				echo _echo($data);
					exit;
				}
				


				$carid_image_z = $post['carid_image_z'];
				$carid_image_f = $post['carid_image_f'];
				$carid_image_s = $post['carid_image_s'];				
				
				//匹配出图片的格式
				if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $carid_image_z, $result)){
					$type = $result[2];
					$new_file = "Uploads/carid/".date('Ymd',time())."/";
					if(!file_exists($new_file)) {
						//检查是否有该文件夹，如果没有就创建，并给予最高权限
						mkdir($new_file, 0700);
					}
					$new_file = $new_file.time().".{$type}";
					if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $carid_image_z)))){
						$carid_image['carid_image_z'] = $new_file;
					}
					// else{
					// 	$data['success'] = error(4009); //请求要求成功返回信息
					// 	echo _echo($data);
					// 	exit;
					// }
				}
				
				if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $carid_image_f, $result)){
					$type = $result[2];
					$new_file = "Uploads/carid/".date('Ymd',time())."/";
					if(!file_exists($new_file)) {
						//检查是否有该文件夹，如果没有就创建，并给予最高权限
						mkdir($new_file, 0700);
					}
					$new_file = $new_file.time().".{$type}";
					if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $carid_image_f)))){
						$carid_image['carid_image_f'] = $new_file;
					}
					// else{
					// 	$data['success'] = error(4009); //请求要求成功返回信息
					// 	echo _echo($data);
					// 	exit;
					// }
				}
				
				if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $carid_image_s, $result)){
					$type = $result[2];
					$new_file = "Uploads/carid/".date('Ymd',time())."/";
					if(!file_exists($new_file)) {
						//检查是否有该文件夹，如果没有就创建，并给予最高权限
						mkdir($new_file, 0700);
					}
					$new_file = $new_file.time().".{$type}";
					if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $carid_image_s)))){
						$carid_image['carid_image_s'] = $new_file;
					}
					// else{
					// 	$data['success'] = error(4009); //请求要求成功返回信息
					// 	echo _echo($data);
					// 	exit;
					// }
				}	
				
		      	$post['carid_image'] = $carid_image;

				$data = $this->userapi_service->user_binding_device($post);
				
				$order_on = time(); //订单编号
				
				//获取一天套餐
				// $where_device_oneday_taocan = array('device_sn' => $post['device_sn']);
				// $device_oneday_taocan =  $this->Device_m->select($where_device_oneday_taocan);

				//获取一天套餐
				// if($device_oneday_taocan[0]['experience'] == 0){
				// 	$get_to_oneday_taocan = $this->device_recharge($post['device_sn'],$order_on,29);
				// 	if($get_to_oneday_taocan['result'] == 0){
				// 		$where_get_to_oneday_taocan = array('device_sn' => $post['device_sn']);
				// 		$data_get_to_oneday_taocan['experience']  = 1;
				// 		$data_get_to_oneday_taocan['experience_time']  = date("YmdHis");
				// 		$this->Device_m->update($where_get_to_oneday_taocan,$data_get_to_oneday_taocan);
				// 	}
				// }

				//实名接口调用
				$shiming = $this->shiming_to_device($post['device_sn']);

				echo _echo($data);
				break;

			case 'PUT':
				
				break;
			case 'DELETE':
				
				break;

			default:
				# code...
				break;
		}

		//$this->load->view('mobile/user_api.php');
	}


	//查询还有多少流量
	public function allflows()
	{
		$spannumber = $this->input->post('spannumber');
		$flows = $this->Device_m->get_ones(array('device_sn'=>$spannumber));
		if (!empty($flows)) {
			$allflow = round($flows['flow'] / 1024 /1024,2);
			echo json_encode(['code'=>1,'flow'=>$allflow]);die;
		}else{
			echo json_encode(['code'=>0,'msg'=>'没有该卡号的信息,请重新输入!']);die;
		}
	}

	//转赠流量-套餐
	public function tranfer(){
	 	$youkahao = $this->input->post('youkahao');//自己卡号
	 	$otherkahao = $this->input->post('otherkahao');//他的卡号
	 	$zznum = $this->input->post('zznum');//数量
	 	$types = $this->input->post('types');
		$cur_date = strtotime(date('Y-m-d'));//当前时间

		/*查询数据*/
		$you_data = $this->Device_m->get_ones(array('device_sn'=>$youkahao));
		$other_data = $this->Device_m->get_ones(array('device_sn'=>$otherkahao));
		if (empty($you_data) || empty($other_data)) {
			echo json_encode(['code'=>1,'msg'=>'当前用户不存在']);die;
		}
		if ($you_data['state'] == 0) {
			echo json_encode(['code'=>1,'msg'=>'当前用户'.$youkahao.'已停用']);die;
		}
		// if ($other_data['state'] == 0) {
		// 	echo json_encode(['code'=>1,'msg'=>'对方用户'.$otherkahao.'已停用']);die;	
		// }
		//天数，包月的
		if ($types == 1) {
			$days = ($you_data['end_time'] - $cur_date) / 86400;

			if ($days > $zznum) {
				$you_time = strtotime(date('Y-m-d',$you_data['end_time'])."-".$zznum." day");//自己减
				$you_update = $this->Device_m->update(array('device_sn'=>$youkahao),array('end_time'=>$you_time));

				$other_time= strtotime(date('Y-m-d',$other_data['end_time'])."+".$zznum." day");//别的加
				$other_update = $this->Device_m->update(array('device_sn'=>$otherkahao),array('end_time'=>$other_time));
				
				$log['my_device_sn'] = $youkahao;
				$log['other_device_sn']=$otherkahao;
				$log['date_num'] = $zznum;
				$log['types'] = $types;
				$log['add_time'] = time();
				$add = $this->db->insert('zhuanzheng_log',$log);
				if ($add) {
					echo json_encode(['code'=>0,'msg'=>'转赠成功']);die;
				}else{
					echo json_encode(['code'=>1,'msg'=>'转赠失败']);die;
				}
			}else{
				echo json_encode(['code'=>1,'msg'=>'数量不足']);die;
			}
		}

		//流量的
		if ($types == 2) {
			$zznums = $zznum * 1024 * 1024;//把G转为KB
			//用自己的总量-已使用+1
			$end_flow = $you_data['flow'] - $you_data['user_flow'] + 1048576;//最终可以转出的

			if ($end_flow > $zznums) {
				$you_flow = $end_flow - $zznums;//自己减
				$you_update = $this->Device_m->update(array('device_sn'=>$youkahao),array('flow'=>$you_flow));

				$other_flow = $other_data['flow'] + $zznums;//别的加
				$other_update = $this->Device_m->update(array('device_sn'=>$otherkahao),array('flow'=>$other_flow));

				$log['my_device_sn'] = $youkahao;
				$log['other_device_sn']=$otherkahao;
				$log['liuliang'] = $zznums;
				$log['types'] = $types;
				$log['add_time'] = time();
				$add = $this->db->insert('zhuanzheng_log',$log);
				if ($add) {
					$other_data = $this->Device_m->get_ones(array('device_sn'=>$otherkahao));
					//没有停用
					$this->ResFlow_state($otherkahao,$other_data['flow'],$other_data['state']);
					//查询剩余
					$you_data = $this->Device_m->get_ones(array('device_sn'=>$youkahao));
					$allflow = round($you_data['flow'] / 1024 /1024,2);
					echo json_encode(['code'=>0,'msg'=>'转赠成功','flow'=>$allflow]);die;

				}else{
					echo json_encode(['code'=>1,'msg'=>'转赠失败']);die;
				}

			}else{
				echo json_encode(['code'=>1,'msg'=>'数量不足']);die;
			}
		}
	 	
	 }

	 public function ResFlow_state($access_number,$flow,$state){
		header("Content-type:text/html;charset=utf-8");
		// header("Content-type:text/xml;charset=utf-8");
		//具体接口参数需参照自管理门户在线文档
		// $access_number='8986111823803770399'; //物联网卡号(149或10649号段)
		$user_id="miaoyue";		//用户名
		$password="V934hoxZwdE2ZmWl";//密码
		$method = "queryPakage";  //接口名-套餐使用量查询
		$arr=array($access_number,$user_id,$password,$method);//加密数组，数组所需参数根据对应的接口文档

		//key值指密钥，由电信提供，每个客户都有对应的key值，key值平均分为三段如下：
	    $key1 = "Jp2";
	    $key2 = "SMp";
	    $key3 = "4Ja";
	    $des=new DesUtils(); //加密工具类实例化

	    $arrOrder=$des->naturalOrdering($arr); //加密数组元素排序
	    $sign = $des->strEnc($arrOrder,$key1,$key2,$key3);
	    $passwords = $des->strEnc($password,$key1,$key2,$key3);
	    $time = time();
		$url = "http://api.e114.xin/m2m_ec/query.do?user_id=".$user_id."&access_number=".$access_number."&sign=".$sign."&passWord=".$passwords."&method=queryPakage";
		// $xml = $this->RequestHttp($url);
		// print_r($xml);exit;
		$reader = new XMLReader(); //实例化XMLReader
		$reader->open($url); //获取xml
		$i=1;
		while ($reader->read()) {
		 if ($reader->nodeType == XMLReader::TEXT) { //判断node类型
		   $m = $i%3;
		   $arr[] = $reader->value;
		   $i++;
		 }
		}
		$already = $arr[5];//已使用 / 1024 /1024
		$left 	 = $arr[6];//剩余 / 1024 /1024
		$total	 = $arr[7];//总量 / 1024 /1024


		//已经关机的
		if ($state == 0) {
			if (intval($flow) > intval($already)) {
				//如果足够就填写已使用的，
				$dataWhere['device_sn'] = $access_number;
				$dataArr['user_flow'] = $already;
				$this->Device_m->update($dataWhere,$dataArr);
				//如果已经停用de
				$this->Functionceshikai($access_number);//调用开机的
			}
		}

		//开机的
		if ($state == 1) {
			if (intval($flow) > intval($already)) {
				//如果足够就填写已使用的，
				$dataWhere['device_sn'] = $access_number;
				$dataArr['user_flow'] = $already;
				$this->Device_m->update($dataWhere,$dataArr);

			}else{
				//如果不够就停用naturalOrdering
				$this->Functionceshiguan($access_number);
			}
		}
		
	}

	//关机
	public function Functionceshiguan($access_number)
	{
		header("Content-type:text/html;charset=utf-8");
		$user_id="miaoyue";		//用户名
		$password="V934hoxZwdE2ZmWl";//密码
		$method = "disabledNumber";  //接口名-套餐使用量查询
		$orderTypeId = 19;
		$arr=array($access_number,$user_id,$password,$method,$orderTypeId);//加密数组，数组所需参数根据对应的接口文档
	    $key1 = "Jp2";
	    $key2 = "SMp";
	    $key3 = "4Ja";
	    $des=new DesUtils(); //加密工具类实例化
		
		$arrOrder=$des->naturalOrdering($arr); //加密数组元素排序
    	$sign = $des->strEnc($arrOrder,$key1,$key2,$key3);
	    $passwords = $des->strEnc($password,$key1,$key2,$key3);

		$urls = "http://api.e114.xin/m2m_ec/query.do?user_id=".$user_id."&access_number=".$access_number."&sign=".$sign."&passWord=".$passwords."&method=".$method."&orderTypeId=".$orderTypeId."";

		$reader = new XMLReader(); //实例化XMLReader
		$reader->open($urls); //获取xml
		$i=1;
		while ($reader->read()) {
		 if ($reader->nodeType == XMLReader::TEXT) { //判断node类型
		   $m = $i%3;
		   $arrs[] = $reader->value;
		   $i++;
		 }
		}
		
		if ($arrs[0] == 0) {
			//关机成功
			$where['device_sn'] = $access_number;
			$res['state'] = 0;
			$this->Device_m->update($where,$res);

			//日入记录-关机
			$file  = './flowlogs/'.date('Y-m-d-H').'guanji.txt';
	        $content = date("Y/m/d h:i:sa").";备注=转赠-关机成功;设备号=".$access_number."\r\n";
	        file_put_contents($file, $content,FILE_APPEND);

			return json_encode(['code'=>3,'msg'=>'转赠关机成功','access_number'=>$access_number]);
		}else{
			//日入记录-关机
			$file  = './flowlogs/'.date('Y-m-d-H').'guanji.txt';
	        $content = date("Y/m/d h:i:sa").";备注=转赠-关机失败;设备号=".$access_number."\r\n";
	        file_put_contents($file, $content,FILE_APPEND);

			return json_encode(['code'=>4,'msg'=>'转赠关机失败','access_number'=>$access_number]);
		}
		
	}
	//开机
	public function Functionceshikai($access_number)
	{
		header("Content-type:text/html;charset=utf-8");
		$user_id="miaoyue";		//用户名
		$password="V934hoxZwdE2ZmWl";//密码
		$method = "disabledNumber";  //接口名-套餐使用量查询
		$orderTypeId = 20;
		$arr=array($access_number,$user_id,$password,$method,$orderTypeId);//加密数组，数组所需参数根据对应的接口文档
	    $key1 = "Jp2";
	    $key2 = "SMp";
	    $key3 = "4Ja";
	    $des=new DesUtils(); //加密工具类实例化
		
		$arrOrder=$des->naturalOrdering($arr); //加密数组元素排序
    	$sign = $des->strEnc($arrOrder,$key1,$key2,$key3);
	    $passwords = $des->strEnc($password,$key1,$key2,$key3);

		$urls = "http://api.e114.xin/m2m_ec/query.do?user_id=".$user_id."&access_number=".$access_number."&sign=".$sign."&passWord=".$passwords."&method=".$method."&orderTypeId=".$orderTypeId."";

		$reader = new XMLReader(); //实例化XMLReader
		$reader->open($urls); //获取xml
		$i=1;
		while ($reader->read()) {
		 if ($reader->nodeType == XMLReader::TEXT) { //判断node类型
		   $m = $i%3;
		   $Arr[] = $reader->value;
		   $i++;
		 }
		}
		
		if ($Arr[0] == 0) {
			//开机成功
			$where['device_sn'] = $access_number;
			$res['state'] = 1;
			$this->Device_m->update($where,$res);
			//日入记录-关机
			$file  = './flowlogs/'.date('Y-m-d-H').'kaiji.txt';
	        $content = date("Y/m/d h:i:sa").";备注=转赠-开机成功;设备号=".$access_number."\r\n";
	        file_put_contents($file, $content,FILE_APPEND);

			return json_encode(['code'=>1,'msg'=>'开机成功','access_number'=>$access_number]);
		}else{
			//日入记录-关机
			$file  = './flowlogs/'.date('Y-m-d-H').'kaiji.txt';
	        $content = date("Y/m/d h:i:sa").";备注=转赠-开机失败;设备号=".$access_number."\r\n";
	        file_put_contents($file, $content,FILE_APPEND);

			return json_encode(['code'=>2,'msg'=>'开机失败','access_number'=>$access_number]);
		}
		
	}
	/**
	wifi接口错误码	描述
	0	无错误
	70001	用户不存在
	70002	MAC验证失败
	70003	DeviceId未找到
	70004	保存记录出错
	70005	读取数据出错
	70006	设备未购买套餐
	70007	没有订单数据（该错误出现在删除了数据库中的对应套餐。正常情况下，套餐不应该从表中delete）
	70008	JSON数据不正确
	70998	数据库异常
	70999	其他异常

	*/

	//充值 //http://www.mifi.com/Mobile/Userapi/user_recharge?device_sn=1546541
	public function user_recharge(){
		//获取微信OPENID 判断登陆 生成用户
		
    	switch ($_SERVER["REQUEST_METHOD"]) {
			case 'GET':
				$get['device_sn'] = $this->input->get('device_sn');
				//$device_sn = 0.$get['device_sn'];
				$device_where = array('device_sn'=>$get['device_sn']);
				$device_data = $this->Device_m->select($device_where);	


				// $get['device_sn'] = '866666030867114';
				//$result = $this->device_auth($get['device_sn']);  //接口验证设备
				
				// if($result['result'] != 0){
				// 	//if($result['result'] != 70006){
				// 		//if($result['result'] != 70007){
				// 			 //if($result['result'] != 70003){
				// 				$data['success'] = error(4010); //请求要求成功返回信息
				// 				echo _echo($data);
				// 				exit;
				// 			 //}
				// 		//}
				// 	//}
				// }

				// if(empty($device_data[0]['user_id'])){
				// 	$data['success'] = error(4006); //请求要求成功返回信息
				// 	echo _echo($data);
				// 	exit;
				// }

				//$recharge_where = '';
				//$order_by = 'id asc';
				
				$datas['user'] = $this->session->userdata('user'); 
				//$data['get_device_meal'] = json_decode($this->get_device_meal()); //套餐
				$datas['device_sn'] = $this->userapi_service->device_sn_get($get);
				if(isset($data['device_sn']['success']['code']) == '4006'){
					$data['success'] = error(4010); //请求要求成功返回信息
					echo _echo($data);
					exit;
				}
				$datas['success'] = success(4000);
				echo _echo($datas);
				break;
			case 'POST':
				
				break;
			case 'PUT':
				
				break;
			case 'DELETE':
				
				break;

			default:
				# code...
				break;
		}
	}


	public function user_recharge_jiance(){
		//获取微信OPENID 判断登陆 生成用户
    	switch ($_SERVER["REQUEST_METHOD"]) {
			case 'GET':
				$get['device_sn'] = $this->input->get('device_sn');
				$device_where = array('device_sn'=>$get['device_sn']);
				$device_data = $this->Device_m->select($device_where);	

				if(empty($device_data[0]['user_id'])){
					$data['success'] = error(4006); //请求要求成功返回信息
					echo _echo($data);
					exit;
				}else{
					$datas['success'] = success(4000);
					echo _echo($datas);
				}
				break;
			case 'POST':
				
				break;
			case 'PUT':
				
				break;
			case 'DELETE':
				
				break;

			default:
				# code...
				break;
		}
	}



	public function user_recharge2(){
		//获取微信OPENID 判断登陆 生成用户
		
    	switch ($_SERVER["REQUEST_METHOD"]) {
			case 'GET':
				$get['device_sn'] = $this->input->get('device_sn');
				//$device_sn = 0.$get['device_sn'];
				$device_where = array('device_sn'=>$get['device_sn']);
				$device_data = $this->Device_m->select($device_where);	


				// $get['device_sn'] = '866666030867114';
				//$result = $this->device_auth($get['device_sn']);  //接口验证设备
				
				// if($result['result'] != 0){
				// 	//if($result['result'] != 70006){
				// 		//if($result['result'] != 70007){
				// 			 //if($result['result'] != 70003){
				// 				$data['success'] = error(4010); //请求要求成功返回信息
				// 				echo _echo($data);
				// 				exit;
				// 			 //}
				// 		//}
				// 	//}
				// }

				if(empty($device_data[0]['user_id'])){
					$data['success'] = error(4006); //请求要求成功返回信息
					echo _echo($data);
					exit;
				}
				
				//$recharge_where = '';
				//$order_by = 'id asc';
				
				$data['user'] = $this->session->userdata('user'); 
				//$data['get_device_meal'] = json_decode($this->get_device_meal()); //套餐
				$data['device_sn'] = $this->userapi_service->device_sn_get($get);
				
				if(isset($data['device_sn']['success']['code']) == '4006'){
					$data['success'] = error(4010); //请求要求成功返回信息
					echo _echo($data);
					exit;
				}

				$data['success'] = success(4000);
				echo _echo($data);
				break;
			case 'POST':
				
				break;
			case 'PUT':
				
				break;
			case 'DELETE':
				
				break;

			default:
				# code...
				break;
		}
	}


	public function package_list(){
		//查询套餐
		$data['get_device_meal'] = json_decode($this->get_device_meal()); //套餐
		echo _echo($data);
	}

	
	//审核返回 //http://wifi.qianlh.com/Mobile/Userapi/user_IDcard_verify?status=0&user_id=10000
	public function user_IDcard_verify(){
		//审核返回  接到值,修改本地用户递交资料状态
		 $status = $this->input->get('status');
		 $user_id = $this->input->get('user_id');
		 if($status == 1){
		 	//实名验证通过 1  修改用户表shiming_tongguo = 1
		 	$data['status'] =  1;
		 	$data['user_id'] =  $user_id;
		 	echo _echo($data);
		 }else{
		 	//实名验证未通过 2  修改用户表shiming_tongguo = 2
		 	$data['status'] =  0;
		 	$data['user_id'] = $user_id;
		 	echo _echo($data);
		 }	
	}


	
	public function weixin_login(){
		$sess_user = $this->session->userdata('user');

		 if($sess_user){
			$url = $this->input->get('url');
			if($url){
				echo '<script>';
				echo 'window.location.href="'.$url.'"';
				echo '</script>';
			}
			exit;
		}

		if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
			$this->session->unset_userdata('user');
            if(!$this->session->userdata('user')){
				//先写死在这里，后期改到数据库
				$appid_where = array('name' => 'appid');
				$secret_where = array('name' => 'secret');
				$appid  = $this->Config_m->select($appid_where);
				$secret  = $this->Config_m->select($secret_where);
				
		       	$appid = $appid[0]['value']; 
		       	$secret = $secret[0]['value'];

                if(!isset($_GET['code'])){
                    $url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]; //这是要回调地址可以有别的写法
                    redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
                    //重定向到以上网址,这是微信给的固定地址.必须格式一致
                }else{
                    //回调成功,获取code,再做请求,获取openid
					$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$_GET['code']}&grant_type=authorization_code";
					$ch = curl_init();//初始化curl        
					curl_setopt($ch, CURLOPT_TIMEOUT, 300);//设置超时
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
					curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
					curl_setopt($ch, CURLOPT_HEADER, FALSE);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);         
					$res = curl_exec($ch);//运行curl，结果以jason形式返回            
					$data = json_decode($res,true);
					curl_close($ch);
					
					if(!isset($data['openid']) || !isset($data['access_token'])){
						$this->weixin_login();
					}
					
					$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid']."&lang=zh_CN";
			        $ch = curl_init();//初始化curl
			        curl_setopt($ch, CURLOPT_TIMEOUT,300);//设置超时
			        curl_setopt($ch, CURLOPT_URL, $url);
			        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
			        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
			        curl_setopt($ch, CURLOPT_HEADER, FALSE);
			        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);         
			        $res = curl_exec($ch);//运行curl，结果以jason形式返回            
			        $data = json_decode($res,true);
					
			        curl_close($ch);
					
			        $this->thirdlogin($data);
					$this->session->userdata('user');
					$url = $this->input->get('url');
					if($url){
						header("Location:".$url.""); 
					}
                }
            }else{
				$this->session->userdata('user');
				$url = $this->input->get('url');
				if($url){
					header("Location:".$url.""); 
				}
			}
        }
	}

	public function thirdlogin($data){
		$weixin_user=$this->Usersweixin_m->select(array('openid'=>$data['openid']));
		if($weixin_user){
			$user=$this->Users_m->select(array('user_id'=>$weixin_user[0]['user_id']));
			$this->session->set_userdata(array('user'=>$user));
		}else{
			$user_id=$this->Users_m->insert(array('nickname'=>$data['nickname'],'reg_time'=>date('Y-m-d H:i:s'),'weixin'=>1));
			$this->Usersweixin_m->insert(array('user_id'=>$user_id,'openid'=>$data['openid']));
			$user=$this->Users_m->select(array('user_id'=>$user_id));
			$this->session->set_userdata(array('user'=>$user));
		}
	}
	
	//佣金计算 
	function yongjin(){
		$where = array('paystate' => 1);
		$orders = $this->Model_m->select('order',$where);
		$device_ids = array();

		foreach ($orders as $key => $value) {
			$device_ids[$key] = $value;
		}
		
		$devices = array();
		foreach ($device_ids as $k => $val) {
			$where_device = array('device_sn' => $val['device_id']);
			$devices = $this->Model_m->select('device',$where_device);
			$devicesa = $devices[0];
			if($devicesa['agent1'] != null){
				$data['agent_user_id'] = $devicesa['agent1'];
				$data['order_id'] = $val['order_on'];
				$data['addtime'] = $val['starttime'];
				$data['device_sn'] = $val['device_id'];
				$data['money'] = $val['order_money']*0.1;
				if($val['goods_on'] == 1){
					$data['flow'] = '1个月流量套餐';
				}
				if($val['goods_on'] == 2){
					$data['flow'] = '3个月流量套餐';
				}
				if($val['goods_on'] == 3){
					$data['flow'] = '6个月流量套餐';
				}
				if($val['goods_on'] == 4){
					$data['flow'] = '12个月流量套餐';
				}
				$data['addtime2'] = strtotime($data['addtime']);
				$devices = $this->Model_m->insert('commission',$data);
			}
			
			if($devicesa['agent2'] != null){
				$data['agent_user_id'] = $devicesa['agent2'];
				$data['order_id'] = $val['order_on'];
				$data['addtime'] = $val['starttime'];
				$data['device_sn'] = $val['device_id'];
				$data['money'] = $val['order_money']*0.1;
				if($val['goods_on'] == 1){
					$data['flow'] = '1个月流量套餐';
				}
				if($val['goods_on'] == 2){
					$data['flow'] = '3个月流量套餐';
				}
				if($val['goods_on'] == 3){
					$data['flow'] = '6个月流量套餐';
				}
				if($val['goods_on'] == 4){
					$data['flow'] = '12个月流量套餐';
				}
				$data['addtime2'] = strtotime($data['addtime']);
				$devices = $this->Model_m->insert('commission',$data);
			}
		}
	} 
	
	
	/**
     * post进行开通1天体验套餐请求
     * @param string $url
     * @param array $post_data
     */

	function device_recharge($device_id,$order_no,$packages) 
	{
		$str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
      	
      	$length = strlen($device_id);
		// if($length != 16){
		// 	$device_id = "0".$device_id."";
		// }
		$get_device_info_url_api_where = array('name' => 'device_recharge_url');
		$get_device_info_uid_api_where = array('name' => 'uid');
		$get_device_info_signkey_api_where = array('name' => 'signkey');

		$device_recharge_url  = $this->Config_m->select($get_device_info_url_api_where);
		$uid  = $this->Config_m->select($get_device_info_uid_api_where);
		$signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
        
        $device_recharge_url = $device_recharge_url[0]['value']; 
       	$id = $uid[0]['value']; 
       	$signkey = $signkey[0]['value'];
       	
        $url = $device_recharge_url;	
        $time = 	time();
        $post_data['password']         = $signkey;
        $post_data['timestamp']        = $time;
        $post_data['username']         = $id;
        $post_data['simId']            = $device_id;
        $post_data['mealId']           = $packages;
        $post_data['countNum']         = 1;

        $data = 'mealId'.$post_data['mealId'].'password'.$post_data['password'].'simId'.$post_data['simId'].'timestamp'.$post_data['timestamp'].'username'.$post_data['username'];
        
        $key = MD5($data);
        $keys = substr($key, 0, 16);
		$post_data['key']      = $keys;

        //$header[] = 'Content-Type: text/html;charset=UTF-8';
        $postUrl  = $url;
        $curlPost =  $post_data;
        //print_r($data);die;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        //curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        //curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
		//print_r($data);die;
        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
            
        return  json_decode($data, true);
    }
	
	
    /**
     * post进行设备查询url请求
     * @param string $url
     * @param array $post_data
     */
    function get_device($device_id) {
        $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
      	$get_device_info_url_api_where = array('name' => 'get_device_info_url');
		$get_device_info_uid_api_where = array('name' => 'uid');
		$get_device_info_signkey_api_where = array('name' => 'signkey');

		$length = strlen($device_id);
		if($length != 16){
			$device_id = "0".$device_id."";
		}

		$get_device_info_url  = $this->Config_m->select($get_device_info_url_api_where);
		$uid  = $this->Config_m->select($get_device_info_uid_api_where);
		$signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
        $get_device_info_url = $get_device_info_url[0]['value']; 
       	$uid = $uid[0]['value']; 
       	$signkey = $signkey[0]['value'];
       	
        $url = $get_device_info_url;

        $post_data['id']         = $uid;
        $post_data['ts']         = time();
        $post_data['device_id']  = $device_id;
		//$post_data['order_no']   = time();
        //$post_data['packages']   = array('package_id' =>2,'count' =>1,'start_time' =>-1);
		
        $sign = hash_hmac('sha512', _echo($post_data), $signkey);
        $header[] = 'Content-Type: application/x-www-form-urlencoded; charset=utf-8';
        $header[] = 'sign:'.$sign;
        $header[] = 'uid:'.$uid;
        $postUrl = $url;
        $curlPost = _echo($post_data);
        
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        //curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
            
        return json_decode($data, true);
    }

    //多个查询设备状态
    function chaxun(){
	    set_time_limit(0);
		$shebei = array(
		// '8986031748204893516'
		);
		$data = array();

	    foreach ($shebei as $key => $value) {
	    	//$data[$value] = $this->device_recharge('8986031748204893516','1525405573350','DFCD6E367D884E0F98118927DF41AB0A');
		   //$data[$value] = $this->device_recharge($value);
		   
		}
	    echo '<pre>';	
	    print_r($data);		

    }

    //单个查询设备状态
    function chaxun2(){

		$shebei = $this->input->get('sn');

		$data = $this->chaxun_to_device($shebei);
		
	    echo '<pre>';
	    $data['youxiaoqi'] = date("Y-m-d H:i:s",$data['last_expire_date'] / 1000);
	    	
	    print_r($data);
    }


    //取所有设备
    function shiming(){
    	ini_set('max_execution_time', '0');
		$get_device_where = array('jihuo' => 1);
		$shebei  = $this->Device_m->select($get_device_where);
	    foreach ($shebei as $key => $value) {
	    	if(!empty($value['user_id']) or $value['user_id'] != 10000){
	    		$data[] = $this->shiming_to_device($value['device_sn']);
	    	}
		}
		
	    echo '<pre>';	
	    print_r($data);		

    }

    //通过用户id获取单个设备信息
	//user_id		用户id
	public function getDeviceByuserid(){
		$sess_user=$this->session->userdata('user');
		if(IS_GET){
			if($sess_user){
				$this->load->model('Device_m');
				$where['user_id']=$sess_user[0]['user_id'];
				$Device=$this->Device_m->select($where);
				$Device_data['success'] = success('4000');	  
				$Device_data['Device'] = $Device;
			    echo _echo($Device_data);
			    exit;
			}else{
				$data['success'] = error('4008');	    	   	
			    echo _echo($data);
			    exit;
			}
	    }else{
			$data['success'] = error('4008');	    	   	
		    echo _echo($data);
		    exit;
		}
		
	}

	/**
     * post进行设备查询url请求
     * @param string $url
     * @param array $post_data
     */
    function device_auth($device_id) {
        $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
		//$device_id = $this->input->get('device_id');
      	$length = strlen($device_id);
		if($length != 16){
			$device_id = "0".$device_id."";
		}
		
		$get_device_info_url_api_where = array('name' => 'device_auth');

		$get_device_info_uid_api_where = array('name' => 'uid');
		$get_device_info_signkey_api_where = array('name' => 'signkey');

		$get_device_info_url  = $this->Config_m->select($get_device_info_url_api_where);
		$uid  = $this->Config_m->select($get_device_info_uid_api_where);
		$signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
        $get_device_info_url = $get_device_info_url[0]['value']; 
       	$uid = $uid[0]['value']; 
       	$signkey = $signkey[0]['value'];
       	
        $url = $get_device_info_url;

        $post_data['id']         = $uid;
        $post_data['ts']         = time();
        $post_data['userName']   = 'user001';
        $post_data['device_id']  = $device_id;
		
        $sign = hash_hmac('sha512', _echo($post_data), $signkey);
        $header[] = 'Content-Type: application/x-www-form-urlencoded; charset=utf-8';
        $header[] = 'sign:'.$sign;
        $header[] = 'uid:'.$uid;
        $postUrl  = $url;
        $curlPost = _echo($post_data);
        
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        //curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $datas = curl_exec($ch);//运行curl 当前套餐名称
        
        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
		$data = json_decode($datas, true);
		return $data;  
		// if($data['result'] != 0){
		// 	$shebei['result'] = $data['result'];
		// 	echo json_encode($shebei);
		// }else{
		// 	$shebei = array();
		// 	$shebei['result'] = $data['result'];          //设备状态 0正常  70003 设备不存在  70006 设备未激活
		// 	$shebei['device_id'] = $data['device_id'];	    //设备编号
		// 	$shebei['package_name'] = $data['package_name'];   //套餐名称
		// 	$shebei['cur_used_flow'] = $data['cur_used_flow'];  //当前套餐已用流量（MB）
		// 	$shebei['cur_month_used_flow'] = $data['cur_month_used_flow'];  //当月已用流量（MB） 
		// 	$shebei['cur_expire_date'] = $data['cur_expire_date'];   //当前套餐有效期
			
		// 	echo json_encode($shebei);
		// }
    }

	/**
     * post进行设备查询url请求
     * @param string $url
     * @param array $post_data
     */
    function get_to_device() {
        $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
		$device_id = $this->input->get('device_id');
     
		$get_device_info_url_api_where = array('name' => 'get_device_info_url');
		$get_device_info_uid_api_where = array('name' => 'uid');
		$get_device_info_signkey_api_where = array('name' => 'signkey');

		$get_device_info_url  = $this->Config_m->select($get_device_info_url_api_where);
		$uid  = $this->Config_m->select($get_device_info_uid_api_where);
		$signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
        $get_device_info_url = $get_device_info_url[0]['value']; 
       	$uid = $uid[0]['value']; 
       	$signkey = $signkey[0]['value'];
       	
        $url = $get_device_info_url;	
        $time = 	time();
        
        $post_data['password']         = $signkey;
        $post_data['simId']            = $device_id;
        //$post_data['simId']            = '8986031748204893516';
        $post_data['timestamp']        = $time;
        $post_data['username']         = $uid;
        $data = 'password'.$post_data['password'].'simId'.$post_data['simId'].'timestamp'.$post_data['timestamp'].'username'.$post_data['username'];

        $key = MD5($data);
        $keys = substr($key, 0, 16);
		$post_data['key']      = $keys;
		
        //$header[] = 'Content-Type: text/html;charset=UTF-8';
        $postUrl  = $url;
        $curlPost =  $post_data;
       
        
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        //curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        //curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $datas = curl_exec($ch);//运行curl 当前套餐名称
       //print_r($datas);die;
        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
		$data = json_decode($datas, true);
		
		if($data['status'] != 0){
			$shebei['result'] = $data['status'];
			echo json_encode($shebei);
		}else{
			$shebei = array();
			$shebei['result'] = $data['status'];          //设备状态 0正常  70003 设备不存在  70006 设备未激活
			$shebei['device_id'] = $data['data'][0]['simId'];	    //设备编号
			$shebei['package_name'] = $data['data'][0]['pckName'];   //套餐名称
			$shebei['cur_used_flow'] = $data['data'][0]['used'];  //当前套餐已用流量（MB）
			$shebei['cur_expire_date'] = $data['data'][0]['endDate'];   //当前套餐有效期
			
			echo json_encode($shebei);
		}
    }
	
	/**
     * post进行设备递交实名请求
     * @param string shiming_to_device
     * @param array $post_data
     */

    function shiming_to_device($device_id){
    	//$device_id = $this->input->get('device_id');

        $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
      	$device_where = array('device_sn' => $device_id);
		$device_info =  $this->Device_m->select($device_where);//设备号信息
		$user_id_where = array();
		if(!empty($device_info[0]['user_id'])){
			$user_id_where = array('user_id' => $device_info[0]['user_id']);
		}else{
			return false; 
		}

		$user_info =  $this->Users_m->select($user_id_where);//用户信息
		$user_idcard_info =  $this->Model_m->select('users_attributes',$user_id_where);//身份证图片
			
      	$length = strlen($device_id);
		if($length != 16){
			$device_id = "0".$device_id."";
		}

		$get_device_info_url_api_where = array('name' => 'shiming_to_device_url');
		$get_device_info_uid_api_where = array('name' => 'uid');
		$get_device_info_signkey_api_where = array('name' => 'signkey');

		$get_device_info_url  = $this->Config_m->select($get_device_info_url_api_where);
		$uid  = $this->Config_m->select($get_device_info_uid_api_where);
		$signkeys  = $this->Config_m->select($get_device_info_signkey_api_where);
		
        $get_device_info_url = $get_device_info_url[0]['value']; 
       	$uid = $uid[0]['value']; 
       	$signkey = $signkeys[0]['value'];

        $url = $get_device_info_url;

        $carid_image_z = '';
        $carid_image_f = '';
        $carid_image_s = '';

        if(!empty($user_idcard_info)){
        	$carid_image_z = $user_idcard_info[0]['carid_image_z'];
        	$carid_image_f = $user_idcard_info[0]['carid_image_f'];
        	$carid_image_s = $user_idcard_info[0]['carid_image_s'];
        	$carid_image_z_base64 = $this->base64EncodeImage($carid_image_z);
        	$carid_image_f_base64 = $this->base64EncodeImage($carid_image_f);
        	$carid_image_s_base64 = $this->base64EncodeImage($carid_image_s);
        }

		if(!empty($carid_image_z) || !empty($carid_image_f) || !empty($carid_image_s) ){
			//数据json化。
			$post_data = '{"id":"'.$uid.'","ts":"'.time().'","device_id":"'.$device_id.'","id_num":"'.$user_info[0]['carid'].'","realname":"'.$user_info[0]['realname'].'","addr":"0","phone":10000000000,"id_pic_front":"'.$carid_image_z_base64.'","id_pic_back":"'.$carid_image_f_base64.'","id_pic_inhand":"'.$carid_image_s_base64.'"}';
			 
			$sign = hash_hmac('sha512',$post_data,$signkey); //sha512转码
			
	        $header[] = 'Content-Type:application/json'; //头文件
	        $header[] = 'sign:'.$sign;
	        $header[] = 'uid:'.$uid;
	        $postUrl  = $url;

	        $curlPost = urlencode($post_data);
	        
	        $ch = curl_init();//初始化curl
	        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
	        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
	        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
	        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
	        //curl_setopt($ch, CURLOPT_HEADER, false);
	        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
	        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
	        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
	        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
	        $datas = curl_exec($ch);//运行curl 当前套餐名称
	        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
	        curl_close($ch);
			$data = json_decode($datas, true);
			return $data; 
		}
		

    } 


	function base64EncodeImage($image_file) {
	  $base64_image = '';
	  $image_info = getimagesize($image_file);
	  $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
	  $base64_image = base64_encode($image_data);
	  return $base64_image;
	}

	/**
     * post进行设备查询url请求
     * @param string $url
     * @param array $post_data
     */

    function chaxun_to_device($device_id) {
        $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
		//$device_id = $this->input->get('device_id');
      	$length = strlen($device_id);
		if($length != 16){
			$device_id = "0".$device_id."";
		}

		$get_device_info_url_api_where = array('name' => 'get_device_info_url');
		$get_device_info_uid_api_where = array('name' => 'uid');
		$get_device_info_signkey_api_where = array('name' => 'signkey');

		$get_device_info_url  = $this->Config_m->select($get_device_info_url_api_where);
		$uid  = $this->Config_m->select($get_device_info_uid_api_where);
		$signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
        $get_device_info_url = $get_device_info_url[0]['value']; 
       	$uid = $uid[0]['value']; 
       	$signkey = $signkey[0]['value'];
       	
        $url = $get_device_info_url;

        $post_data['id']         = $uid;
        $post_data['ts']         = time();
        $post_data['device_id']  = $device_id;
		
        $sign = hash_hmac('sha512', _echo($post_data), $signkey);
        $header[] = 'Content-Type: application/x-www-form-urlencoded; charset=utf-8';
        $header[] = 'sign:'.$sign;
        $header[] = 'uid:'.$uid;
        $postUrl  = $url;
        $curlPost = _echo($post_data);
        
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        //curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $datas = curl_exec($ch);//运行curl 当前套餐名称
        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
		$data = json_decode($datas, true);
		return $data;  
    }
	

	/**
     * post进行套餐查询url请求
     * @param string $url
     * @param array $post_data
     */
    function taocan_to_device() {
        $str_cookie = isset($ext_params['str_cookie']) ? $ext_params['str_cookie'] : '';$ch = curl_init();//初始化curl
		$device_id = $this->input->get('device_id');

		$get_device_info_url_api_where = array('name' => 'taocan_to_device_url');
		$get_device_info_uid_api_where = array('name' => 'uid');
		$get_device_info_signkey_api_where = array('name' => 'signkey');

		$taocan_to_device_url  = $this->Config_m->select($get_device_info_url_api_where);
		$uid  = $this->Config_m->select($get_device_info_uid_api_where);
		$signkey  = $this->Config_m->select($get_device_info_signkey_api_where);
		
        $taocan_to_device_url = $taocan_to_device_url[0]['value']; 
       	$uid = $uid[0]['value']; 
       	$signkey = $signkey[0]['value'];
       	
        $url                           = $taocan_to_device_url;	
        $time                          = time();
        $post_data['password']         = $signkey;
        $post_data['timestamp']        = $time;
        $post_data['username']         = $uid;

        $data = 'password'.$post_data['password'].'timestamp'.$post_data['timestamp'].'username'.$post_data['username'];
        $key = MD5($data);
        $keys = substr($key, 0, 16);
		$post_data['key']      = $keys;
		
        //$header[] = 'Content-Type: text/html;charset=UTF-8';
        $postUrl  = $url;
        $curlPost =  $post_data;
      // print_r($curlPost);die;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//要求结果为字符串且输出到屏幕上
       // curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_COOKIE, $str_cookie);
        //curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $datas = curl_exec($ch);//运行curl 当前套餐名称
		print_r($datas);die;
        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
		$data = json_decode($datas, true);
		return $data; 
    }

    /**
     * 发送阿里云短信
     * @param string $url
     * @param array $post_data
     */
    function sendsmsgo($mobile,$nickname,$taocan,$lastday){
    	$SmsDemo = new SmsDemo();
    	// 调用示例：
		//set_time_limit(0);
		//header('Content-Type: text/plain; charset=utf-8');

		$response = $SmsDemo->sendSms($mobile,$nickname,$taocan,$lastday);
		// echo "发送短信(sendSms)接口返回的结果:\n";
		// print_r($response);

		// sleep(2);

		// $response = $SmsDemo->querySendDetails();
		// echo "查询短信发送情况(querySendDetails)接口返回的结果:\n";
		// print_r($response);
    }

	//加密解密测试方法 
	function ssencode() {
		$content = "1";
		$mifen = jiami($content);
		//echo "string : " . $content . " <br />";
		echo "encode : " . (jiami($content)) . '<br />';
		echo "name : " . (jiemi($mifen)) . '<br />';
	}


}
    

